package wCount;

import java.util.List;
import java.util.Map;
import wCount.FileDeal;
import wCount.WordDeal;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ScDeal {
	String[] args;			//储存输入的数组
	int nexit,mnum;			//nexit表示-n设定的输出的单词数量，mnum表示统计的词组长度
	int nhappen=0,mexit=0;	//nhappen表示-n有触发，mexit表示-m有触发
	public String w = "";			//储存输出
	public ScDeal(String[] args) {		//初始化
		this.args=args;
	}
	public void judge() throws IOException {		//判断输入的是-i,-n,-m
		for (int i = 0; i < args.length; i++) {
			switch(args[i]) {
			case "-i":ideal(i);i++;
				break;
			case "-m":mdeal(i);i++;
				break;
			case "-n":ndeal(i);i++;
				break;
			case "-o":odeal(i);i++;
				break;
			default:
				System.out.println("输入错误代码");
				break;
			}
		}
		
		
		
	}
	public void ideal(int num) throws IOException {		//-i主要是读取文件
		
		String file = args[num+1];
		FileDeal fd = new FileDeal();
		String[] wFreq,WGFreq;
		List sortMap,sortGroup;

		String text = fd.FileToString(file);
		WordDeal wd = new WordDeal(text);
		
		int charNum = wd.getCharCount();
		int wordCount = wd.getWordCount();
		int ValidLine = wd.getLineCount();
		Map<String, Integer> wordFreq = wd.getWordFreq();
		Map<String, Integer> wordGroupFreq = wd.getWordGroupFreq(mnum);
		sortMap = wd.sortMap(wordFreq);
		sortGroup = wd.sortMap(wordGroupFreq);
		wFreq = wd.ListToArray(sortMap);
		WGFreq = wd.ListToArray(sortGroup);
		
		if(nhappen==1) {       //判断是否有-n出现，限定输出
			
			for (int i = 0; i < nexit; i++) {
				w = w + wFreq[i] + "\r\n";
			}
			System.out.println(w);
			
		}else if(mexit==1) {	//判断是否有-m出现，限定输出
			w = charNum + "\r\n" + wordCount + "\r\n" + ValidLine + "\r\n";
			for (int i = 0; i < WGFreq.length; i++) {
				w = w + WGFreq[i] + "\r\n";
			}
			System.out.println(w);
			
		}else {					//都没有限制直接全部输出
			w = charNum + "\r\n" + wordCount + "\r\n" + ValidLine + "\r\n";
			for (int i = 0; i < wFreq.length; i++) {
				w = w + wFreq[i] + "\r\n";
			}
			System.out.println(w);
			
		}
	}
	public void mdeal(int i) {		//判断-m是否出现储存后面的数字
		mnum=Integer.parseInt(args[i+1]);
		mexit=1;
		
	}
	public void ndeal(int i) {		//判断-n是否出现储存后面的数字
		nexit=Integer.parseInt(args[i+1]);
		nhappen=1;
	}
	public void odeal(int i) throws IOException {	//-o的话直接把w里的储存到txt文档里
		String file = args[i+1];
		
		File writename = new File(file);
		writename.createNewFile(); 
		BufferedWriter out = new BufferedWriter(new FileWriter(writename));
		out.write(w);

		out.flush();
		out.close();
	}
}
